﻿using TT.CIT.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Networking.Proximity;
using System.Threading.Tasks;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace TT.CIT
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Configuracao : Page, IDisposable
    {
        private Common.TTSettings config = null;
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        private ProximityDevice _proximitydevice;

        public Configuracao()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            config = new TTSettings();
            _proximitydevice = ProximityDevice.GetDefault();
        }

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// Gets the view model for this <see cref="Page"/>.
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
        /// <param name="e">Event data that provides an empty dictionary to be populated with
        /// serializable state.</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper registration

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);

            //Carrega as configurações salvas
            if (config != null)
            {
                if (_proximitydevice == null)
                {
                    NFC.IsEnabled = false;
                    config.NFCSetting = false;
                }
                else
                {
                    NFC.IsEnabled = true;
                    NFC.IsOn = config.NFCSetting;
                }

                GPS.IsOn = config.GPSSetting;

                if (GPS.IsOn)
                {
                    LocaisGPS.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    HorarioGPS.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                else
                {
                    LocaisGPS.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    HorarioGPS.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
                Predio9.IsChecked = config.Predio9Setting;
                Predio16.IsChecked = config.Predio16Setting;
                Predio23A.IsChecked = config.Predio23ASetting;
                Predio23B.IsChecked = config.Predio23BSetting;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);

            // If the navigation is external to the app do not clean up.
            // This can occur on Phone when suspending the app.
            if (e.NavigationMode == NavigationMode.Forward && e.Uri == null)
            {
                return;
            }
            Dispose();
        }

        #endregion

        private void ContentRoot_Loaded(object sender, RoutedEventArgs e)
        {
            TTSettings settings = (TTSettings)this.Resources["appSettings"];

            //settings.EmailSetting = textBoxEmail.Text;
        }

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));
        }

        private void GPS_Toggled(object sender, RoutedEventArgs e)
        {
            if (config != null)
            {
                config.GPSSetting = GPS.IsOn;
                if (GPS.IsOn)
                {
                    LocaisGPS.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    HorarioGPS.Visibility = Windows.UI.Xaml.Visibility.Visible;
                }
                else
                {
                    LocaisGPS.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    HorarioGPS.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
            }
        }

        private void NFC_Toggled(object sender, RoutedEventArgs e)
        {
            if (config != null)
            {
                config.NFCSetting = NFC.IsOn;
            }
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            StatusTag.Text = "";
            Dispose();
        }

        public void Dispose()
        {
            if (config != null)
            {
                config = null;
            }

            if (navigationHelper != null)
            {
                navigationHelper = null;
            }

            if (_proximitydevice != null)
            {
                _proximitydevice = null;
            }
        }

        private void Predio23A_Checked(object sender, RoutedEventArgs e)
        {
            if (config != null)
            {
                config.Predio9Setting = false;
                config.Predio16Setting = false;
                config.Predio23BSetting = false;
                config.Predio23ASetting = Predio23A.IsChecked.Value;
            }
        }

        private void Predio23B_Checked(object sender, RoutedEventArgs e)
        {
            if (config != null)
            {
                config.Predio9Setting = false;
                config.Predio16Setting = false;
                config.Predio23ASetting = false;
                config.Predio23BSetting = Predio23B.IsChecked.Value;
            }
        }

        private void Predio16_Checked(object sender, RoutedEventArgs e)
        {
            if (config != null)
            {
                config.Predio9Setting = false;
                config.Predio23ASetting = false;
                config.Predio23BSetting = false;
                config.Predio16Setting = Predio16.IsChecked.Value;
            }
        }

        private void Predio9_Checked(object sender, RoutedEventArgs e)
        {
            if (config != null)
            {
                config.Predio16Setting = false;
                config.Predio23ASetting = false;
                config.Predio23BSetting = false;
                config.Predio9Setting = Predio9.IsChecked.Value;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (_proximitydevice != null)
            {
                _proximitydevice.SubscribeForMessage("WriteableTag", WriteableTagDetected);
                NotifyUser("Aproxime a Tag NFC para gravar...");
            }

            //Windows.Networking.Proximity.ProximityDevice proximityDevice;

            //proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            //if (proximityDevice != null)
            //{

            //    //// The format of the app launch string is: "<args>\tWindows\t<AppName>".
            //    //// The string is tab or null delimited.

            //    //// The <args> string can be an empty string ("").
            //    //string launchArgs = "checkin";

            //    //// The format of the AppName is: PackageFamilyName!PRAID.
            //    //string praid = "ee5e148f-2fb7-44a6-8eef-42f554f4b679"; // The Application Id value from your package.appxmanifest.

            //    //string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

            //    //string launchAppMessage = launchArgs + "\tWindows\t" + appName;

            //    //var dataWriter = new Windows.Storage.Streams.DataWriter();
            //    //dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
            //    //dataWriter.WriteString(launchAppMessage);
            //    //var launchAppPubId = proximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer());

            //    //if(launchAppPubId > 0)
            //    //{

            //    //}
            //}
        }

        private void WriteableTagDetected(ProximityDevice sender, ProximityMessage message)
        {
            var args = "checkin";
            //var appId = Windows.ApplicationModel.Store.CurrentApp.AppId;
            var appId = "{62b3209e-c806-48b5-b1d6-840dcaff0c7f}";
            string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName; // +"!" + appId;
            var launchAppMessage = args + "\tWindowsPhone\t" + appId;

            var dataWriter = new Windows.Storage.Streams.DataWriter();
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
            dataWriter.WriteString(launchAppMessage);
            ProximityDevice.GetDefault().PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer(), MesssageTransmitted);
        }

        private void MesssageTransmitted(ProximityDevice sender, long messageId)
        {
            ProximityDevice.GetDefault().StopPublishingMessage(messageId);
            NotifyUser("Tag NFC gravada com sucesso!");
        }

        public async void NotifyUser(string Message)
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                StatusTag.Text = Message;
            });
        }

        private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
        {

        }
    }
}
